package liuliu.throughwaring.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;

import net.tsz.afinal.FinalDb;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import liuliu.custom.method.Utils;
import liuliu.throughwaring.control.net.HttpTask;
import liuliu.throughwaring.control.task.QueryTask;
import liuliu.throughwaring.control.task.addTask;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.InvokeReturn;
import liuliu.throughwaring.model.NoticeModel;
import liuliu.throughwaring.ui.map.DingWeiListener;
import liuliu.throughwaring.view.Util;

/**
 * Created by Administrator on 2016/1/18.
 */
public class NoticeHandlerService extends Service {
    FinalDb db;
    private Handler handler = new Handler();
    NoticeModel noticeModelService;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new DingWeiListener();
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;


    @Override
    public void onCreate() {
        db = FinalDb.create(this);

        new Thread(runnable).start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                System.out.println("notice  handler service");
                LocationStart();//定位
                getURLNotice();//获取通知通告

                //上传当前位置
                UpdateLocation();
                //获取推送的企业信息
                getCompanyNew();

            }
        };
        super.onCreate();
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //System.out.println("notice  handler service runnable");
            Message msg = handler.obtainMessage();
            msg.obj = 0;
            handler.sendMessage(msg);
            handler.postDelayed(this, 60000);
        }
    };

    private void UpdateLocation() {
        String eastPoint = Utils.ReadString("Longitud");//东经
        String northPoint = Utils.ReadString("Latitude");//北纬


        CoordinateConverter converter = new CoordinateConverter(this);
        converter.from(CoordinateConverter.CoordType.BAIDU);
//        eastPoint="23.369";
//        northPoint="23.254";
        if (eastPoint.equals("") || northPoint.equals("")) {
            //System.out.println("kong notice;;;");
        } else {
            Double longitud = Double.parseDouble(eastPoint);
            Double latitude = Double.parseDouble(northPoint);
            DPoint point = new DPoint();
            point.setLatitude(latitude);
            point.setLongitude(longitud);

            DPoint newPoint = null;
            try {
                converter.coord(point);
                newPoint = converter.convert();
                addTask task = new addTask(NoticeHandlerService.this);
                task.UpdateLocation(newPoint.getLongitude() + "", newPoint.getLatitude() + "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //高德地图定位
    public void LocationStart() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听

        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void getURLNotice() {
        /*
         * 获取未下载的通知通告
         */
        HttpTask task = new HttpTask(NoticeHandlerService.this);
        //检查最后一个消息的时间
        String lastTime = "1900-01-01 00:00:00";
        String time;
        List<NoticeModel> list = db.findAllByWhere(NoticeModel.class, " 1=1 order by NoticeCreateTime desc");
        if (list != null) {
            if (list.size() > 0) {
                time = list.get(0).getNoticeCreateTime();
            } else {
                time = lastTime;
            }
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = formatter.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            lastTime = Utils.getDateString(String.valueOf(date.getTime() + 1000));
            task.start("GetNotices", "LastModified=" + lastTime, "NoticeModel", true, new HttpTask.TaskListener() {
                @Override
                public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                    if (result && invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            List lists = invokeReturn.getData();
                            boolean haveNew = false;
                            if (lists.size() > 0) {
                                for (int i = 0; i < lists.size(); i++) {
                                    NoticeModel model = (NoticeModel) lists.get(i);
                                    List<NoticeModel> list = db.findAllByWhere(NoticeModel.class, "NoticeId='" + model.getNoticeId() + "'");
                                    if (null != list) {
                                        if (list.size() == 0) {
                                            model.setIsRead(0);
                                            model.setNoticeCreateTime(Utils.getDateString(model.getNoticeCreateTime()));
                                            db.save(model);
                                            haveNew = true;
                                        }
                                    }
                                }
                                //gf.FaceShow(haveNew);
                            }
                        }
                    }
                }
            });
        }
    }

    private void getCompanyNew() {
        /*
         * 获取未下载的通知通告
         */
        HttpTask task = new HttpTask(NoticeHandlerService.this);
        //检查最后一个消息的时间

        task.start("PushCompany", "", "CompanyModel", true, new HttpTask.TaskListener() {
            @Override
            public void onTaskResult(boolean result, InvokeReturn invokeReturn) {
                if (result) {
                    if (invokeReturn != null) {
                        if (invokeReturn.isSuccess()) {
                            //System.out.println("新企业信息下载成功");
                            //List<CompanyModel> newCompanys = new ArrayList<CompanyModel>();
                            for (int i = 0; i < invokeReturn.getData().size(); i++) {
                                //newCompanys.add((CompanyModel) invokeReturn.getData().get(i));
                                CompanyModel companyModel = (CompanyModel) invokeReturn.getData().get(i);
                                List<CompanyModel> cms = db.findAllByWhere(CompanyModel.class, "CompanyId= '" + companyModel.getCompanyId() + "'");
                                if (cms.size() > 0) {
                                    db.update(companyModel);
                                } else {
                                    db.save(companyModel);
                                }
                            }
                        } else {
                            //错误提示信息
                            //System.out.println("新企业信息:" + invokeReturn.getMessage());
                        }
                    }
                } else {
                    //System.out.println("新企业信息下载失败");
                }
            }
        });
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        onDestroy();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // mLocationClient.stopLocation();//停止定位
        mLocationClient.onDestroy();//销毁定位客户端。
        handler.removeCallbacks(runnable);
    }
}